package adc.budget.ui.web.wicket;

import java.util.Set;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.spring.injection.annot.SpringBean;

import adc.app.ui.wicket.BoEditPanel.ICancelCallback;
import adc.app.ui.wicket.BoEditPanel.ISaveCallback;
import adc.app.ui.wicket.BoListPanel.IAddCallback;
import adc.app.ui.wicket.BoListPanel.IDeleteCallback;
import adc.app.ui.wicket.BoListPanel.IEditCallback;
import adc.app.ui.wicket.model.BoModel;
import adc.budget.spec.bo.IAccount;
import adc.budget.spec.bs.IAccountBs;
import adc.budget.ui.web.wicket.account.AccountEditPanel;
import adc.budget.ui.web.wicket.account.AccountListPanel;
import adc.budget.ui.web.wicket.account.IMsgsAccount;

public class AccountPage extends LayoutPage implements IAddCallback, IEditCallback<IAccount>, IDeleteCallback, ISaveCallback<IAccount>, ICancelCallback {

    private static final long serialVersionUID = 1L;

    @SpringBean
    private IAccountBs accountBs;
    private final AccountListPanel listPanel;
    
    public AccountPage() {
        super();
        listPanel = new AccountListPanel("accounts");
        listPanel.setAddCallback(this).setEditCallback(this).setDeleteCallback(this);
        listPanel.setOutputMarkupId(true);
        add(listPanel);
        setTitle(new ResourceModel(IMsgsAccount.ACCOUNTS));
    }

    @Override
    public void add(AjaxRequestTarget target) {
        final IModel<IAccount> Account = new BoModel<IAccount>(IAccountBs.class);
        openEditDialog(target, Account);
    }

    @Override
    public void edit(AjaxRequestTarget target, IModel<IAccount> Account) {
        openEditDialog(target, Account);
    }

    @Override
    public void delete(AjaxRequestTarget target, Set<Long> ids) {
        for (Long id : ids) {
            final IAccount at = accountBs.byId(id);
            if (at != null) {
                accountBs.delete(at);
            }
        }
        listPanel.updateTable(target);
    }

    @Override
    public void save(AjaxRequestTarget target, Form<IAccount> form) {
        accountBs.save(form.getModelObject());
        getModalWindow().close(target);
        listPanel.updateTable(target);
    }

    @Override
    public void cancel(AjaxRequestTarget target) {
        getModalWindow().close(target);
    }

    private void openEditDialog(final AjaxRequestTarget target, final IModel<IAccount> account) {
        final ModalWindow md = getModalWindow();
        md.setContent(new AccountEditPanel(md.getContentId()).setSaveCallback(this)
                .setCancelCallback(this).setModel(account));
        md.setInitialWidth(300);
        md.setInitialHeight(220);
        md.setTitle(new ResourceModel(IMsgsAccount.ACCOUNT));
        md.show(target);
    }

}
